<!-- 批次检验管理 -->
<template>
  <BaseMainSlot>
    <template v-slot:searchbox>
      <!-- <div class="search-box" v-if="userType == '1'">
        <div class="search-box flex f_between f_end">
          <div class="searchModule flex">
            <div class="search-box-condition felx">
              <div class="label">选择时间：</div>
              <el-date-picker v-model="searchParams.timeList" type="daterange" align="left" unlink-panels
                value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                :picker-options="pickerOptions">
              </el-date-picker>
            </div>
            <div class="search-box-condition felx">
              <div class="label">选择批次：</div>
              <el-select filterable clearable v-model="searchParams.productionBatchId" clearable>
                <el-option v-for="batchitem in batchList" :key="batchitem.productionBatchId" :label="batchitem.mnecode"
                  :value="batchitem.productionBatchId" />
              </el-select>
            </div>
            <div class="search-box-condition felx">
              <div class="label">请选择检验人：</div>
              <el-select filterable clearable v-model="searchParams.staffName" clearable>
                <el-option v-for="(staffObj, index) in staffList" :key="index" :label="staffObj.staffName"
                  :value="staffObj.staffName">
                </el-option>
              </el-select>
            </div>
          </div>
          <div class="operation flex f_between">
            <div class="search-box-btns query-btn" @click.stop="queryPageList">
              <i class="el-icon-search"></i>
              <p>查询</p>
            </div>
            <div class="search-box-btns reset-btn" @click.stop="resetSearchParams">
              <i class="el-icon-refresh-left"></i>
              <p>重置</p>
            </div>
            <div class="search-box-btns output-btn" @click.stop="add('add')" v-if="userType == '2'">
              <i class="el-icon-printer"></i>
              <p>添加</p>
            </div>
          </div>
        </div>
      </div> -->
      <el-collapse v-model="activeName" accordion @change="handleChange">
        <el-collapse-item name="1">
          <template slot="title">
            <div class="select-btns search-btns" @click.stop="changeSelect()">
              <i class="el-icon-circle-check"></i>
              <p v-if="activeName === '1'">收起筛选</p>
              <p v-if="activeName === ''">展开筛选</p>
            </div>
          </template>
          <div class="search-btn search-btns" @click.stop="queryPageList(), searchPage()">
            <i class="el-icon-circle-check"></i>
            <p>查询</p>
          </div>
          <div class="select-box-content">
            <div class="select-box-content-name">选择批次</div>
            <el-select filterable clearable v-model="searchParams.productionBatchId" clearable>
              <el-option v-for="batchitem in batchList" :key="batchitem.productionBatchId" :label="batchitem.mnecode"
                :value="batchitem.productionBatchId" />
            </el-select>
          </div>
          <div class="select-box-content">
            <div class="select-box-content-name">选择检验人</div>
            <el-select filterable clearable v-model="searchParams.staffName" clearable>
              <el-option v-for="(staffObj, index) in staffList" :key="index" :label="staffObj.staffName"
                :value="staffObj.staffName">
              </el-option>
            </el-select>
          </div>
          <div class="select-box-content">
            <div class="select-box-content-name">选择时间</div>
            <el-date-picker v-model="searchParams.timeList" type="daterange" align="left" unlink-panels
              value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
              :picker-options="pickerOptions">
            </el-date-picker>
          </div>
        </el-collapse-item>
      </el-collapse>
    </template>

    <template v-slot:btnsBar>
      <ChooseHomeBase :categoryList="categoryList" @searchBar="searchBar" v-if="userType == '1'"></ChooseHomeBase>
      <ActionBar :add-active="addActive" :hasDel="false" :page-no="162" v-if="userType == '2'" @add="add('add')"
        @del="del" />
    </template>
    <template v-slot:content>
      <Table :propList="propList" :listData="tableData">
        <template v-slot:footer>
          <Pagination :page-size="pageSize" :current-page="currentPage" :total-size="totalSize"
            @changeCurrentPage="changeCurrentPage" />
        </template>
        <template v-slot:banchName="{ row }">
          <div class="table-btns-box" v-if="row.generalInspectionId && row.productionBatchDTO">
            <p>{{ row.productionBatchDTO.mnecode }}</p>
          </div>
        </template>
        <template v-slot:whetherNormal="{ row }">
          <div class="table-btns-box" v-if="row.generalInspectionId">
            <p>{{ row.whetherNormal ? '正常' : '异常' }}</p>
          </div>
        </template>
        <template v-slot:operation="{ row }">
          <div class="table-btns-box" v-if="row.generalInspectionId">
            <div class="table-btns edit-btns">
              <p @click="downloadFile(row.reportFileIdList)">导出</p>
            </div>
          </div>
          <div class="table-btns-box" v-if="row.generalInspectionId && userType == '2'">
            <div class="table-btns edit-btns">
              <p @click="handleDelete(row)">删除</p>
            </div>
          </div>
        </template>
      </Table>
      <AddDialog :show="showAddDialog" :nowChanceStau="nowChanceStau" :batchList="batchList" :staffList="staffList"
        :editObject="dialogObject" @cancelDialog="cancelDialog" @closeDialog="closeDialog"></AddDialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import ActionBar from "@/components/ActionBar/index.vue";
import Pagination from "@/components/Pagination";
import Table from "@/components/table/index.vue";
import AddDialog from "./component/add-edit-dialog";
import BaseMainSlot from "@/components/BaseMainSlot/kong-new2.vue";
import ChooseHomeBase from "@/components/ChooseHomeBase/index.vue"

import { mymixin } from "@/utils/mixin";
import { mapGetters } from "vuex";

import inspectionReportApi from "@/api/inspection-management/inspection-report-management";
import demoApi from "@/api/document";
import AbnormalDeathApi from "@/api/health-management/abnormal-death-management";
import StaffApi from "@/api/basic-info-manage/staff"; //员工
import BatchApi from "@/api/batch-mange/index"; //批次
export default {
  name: "InspectionReport",
  components: { ActionBar, Pagination, Table, BaseMainSlot, ChooseHomeBase, AddDialog },
  mixins: [mymixin],
  data () {
    return {
      userType: '', //1:运营  2:基地
      activeName: '1',
      totalSize: 0,
      nowChanceStau: '',
      showAddDialog: false,
      dialogObject: {},
      categoryList: [],
      searchParams: {
        timeList: [],
        staffName: '',
        productionBatchId: ''
      },
      batchList: [],
      staffList: [],
      checkedIdList: [],
      listData: [],
      propList: [
        { label: "批次编号", minWidth: "80", slotName: "banchName" },
        { prop: "checkName", label: "检验名称", minWidth: "80" },
        { prop: "staffName", label: "检验人", minWidth: "80" },
        { prop: "remark", label: "检验说明", minWidth: "80" },
        { label: "是否正常", minWidth: "80", slotName: "whetherNormal" },
        { prop: "uploadDateTime", label: "检验时间", minWidth: "80" },
        { label: "操作", minWidth: "80", slotName: "operation" },
      ],
      pickerOptions: {
        shortcuts: [{
          text: '最近一天',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一周',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近30天',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {},
  created () {
    this.categoryList = JSON.parse(sessionStorage.getItem('homeBaseList'))
    this.userType = sessionStorage.getItem('userType')  //1:运营  2:基地
    console.log('userType', this.userType)
  },
  mounted () {
    this.queryPageList();
    this.queryEssentialData();
  },
  methods: {
    searchPage () {
      this.currentPage = 1
      this.queryPageList();
      setTimeout(() => {
        this.queryPageList();
      }, 200);
    },
    //切换基地
    searchBar (data) {
      this.queryPageList();
      this.queryEssentialData();
      this.resetSearchParams();
    },
    //删除
    handleDelete (data) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        
      }).then(() => {
        inspectionReportApi.delByIdOMS({ id: data.generalInspectionId }).then(res => {
          if (res.success) {
            this.$message.success("删除成功");
            this.queryPageList();
          } else {
            this.$message.error("删除失败");
          }
        });
      }).catch(() => {
        this.$message("取消删除");
      });
    },
    //导出文件
    downloadFile (fileIdList) {
      fileIdList.forEach(async id => {
        id && await demoApi.fileDownload({ 'fileId': id }).then(res => {
          this.getFileNameAndDownload(res)
        })
      })
      fileIdList.length > 0 && this.$message.success("导出成功");
    },
    //获取添加表单下拉项
    queryEssentialData () {
      Promise.all([
        BatchApi.queryByCondition(),  //获取批次
        StaffApi.queryByCondition()  //获取员工
      ]).then(resList => {
        this.batchList = resList[0].data;
        this.staffList = resList[1].data;
        console.log('批次:', this.batchList)
        console.log('员工:', this.staffList)
      }).catch(err => {
        console.log(err)
      })
    },
    closeDialog () {
      this.nowChanceStau = ''
      this.showAddDialog = false
      this.queryPageList();
    },
    add (nowChanceStau) {
      this.showAddDialog = true
      this.nowChanceStau = nowChanceStau
      this.dialogObject = {
        remark: '', //检验说明
        checkType: '',//检验类型
        staffName: '', //检验人
        whetherNormal: '', //是否合格
        uploadDateTime: '', //检验时间
        reportFileIdList: [], //文件列表
      }
    },
    cancelDialog () {
      this.nowChanceStau = ''
      this.showAddDialog = false
    },
    shortcutsSelected (item) {
      console.log(item.onClick());
    },
    resetSearchParams () {
      this.searchParams = {
        timeList: [],
        staffName: '',
        productionBatchId: ''
      }
      this.queryPageList();
    },
    exportData () {
      AbnormalDeathApi.export().then(res => {
        // data就是接口返回的文件流
        let data = res
        if (data) {
          this.getFileNameAndDownload(res)
        } else {
          console.log('error', data)
        }
      })
    },

    queryPageList () {
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: { ...this.searchParams }
      };
      if (this.searchParams.timeList?.length == 2) {
        params.entity.startTime = this.searchParams.timeList[0] + ' 00:00:00'
        params.entity.endTime = this.searchParams.timeList[1] + ' 23:59:59'
      }
      params.entity.homeBaseId = sessionStorage.getItem('homeBaseId')
      inspectionReportApi.queryPageByConditionOMS(params).then(res => {
        if (res.success === true) {
          let data = res.data || {};
          this.totalSize = data.totalElements;
          this.tableData = data.content;
          this.addblankmet();
          console.log(this.tableData)
        }
      });
    },
    changeCurrentPage (currentPage) {
      this.currentPage = currentPage;
      this.queryPageList();
    },
  }
};
</script>

<style lang="scss" scoped>
@import "../style/index.scss";

::v-deep .common-layout {
  margin-top: 30px;
  height: 540px !important;
}

::v-deep .el-range-separator {
  color: #ccc;
  line-height: 28px !important;
}

.search-box {
  width: 100%;
}

.flex {
  display: flex;
  align-items: center;
}

.f_end {
  align-items: flex-start
}

.f_between {
  justify-content: space-between;
}

.f_around {
  justify-content: space-around;
}

.searchModule {
  flex-wrap: wrap;
}

.search-box-condition {
  margin-bottom: 5px;

  .label {
    padding-right: 10px;
    line-height: 35px;
    color: #59a1e8;
  }
}

::v-deep .tab-select {
  margin: 0 !important;
}
</style>
